import time

import jwt
from flask import current_app


class JwtTool():
    def create(self, payload, ex=3600):
        """
        生成jwt
        :param payload:
        :return:
        """
        payload['exp'] = int(time.time()) + (ex * 24 * 30)
        print(payload)
        secret_key = current_app.config.get('SECRET_KEY')
        token = jwt.encode(payload, key=secret_key, algorithm='HS256')
        print(token)
        return token

    def valid(self, token):

        secret_key = current_app.config.get('SECRET_KEY')
        try:
            time.sleep(2)
            payload = jwt.decode(token, secret_key, algorithms='HS256')
            print(payload)
            return payload
        except Exception as e:
            print(e)
            return False


if __name__ == '__main__':
    from app import app

    with app.app_context():
        j = JwtTool()
        token_jwt = j.create({'aaa': 'bbb'})

        j.valid(token_jwt)
